package com.zhkj.txg.utils

import android.app.Activity
import android.content.Context
import com.alipay.sdk.app.PayTask
import com.google.gson.annotations.SerializedName
import com.zhkj.lib.config.WX_APP_ID
import com.zhkj.lib.utils.ToastUtil
import com.zhkj.txg.R
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

object PayUtils {
    /**
     * 支付宝支付
     * @param orderInfo 后台返回的订单信息
     * @param onSuccess 支付成功时回调
     * @param onFailure 支付失败时回调
     */
    fun aliPay(
        activity: Activity,
        orderInfo: String,
        onSuccess: () -> Unit,
        onFailure: (desc: String) -> Unit
    ): Disposable {
        return Observable.just(orderInfo)
            .map {
                PayTask(activity).payV2(it, true)
            }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                when (it["resultStatus"]) {
                    AliPayResult.SUCCESS.code -> onSuccess()
                    AliPayResult.FAILURE.code -> onFailure(it["memo"] ?: AliPayResult.FAILURE.desc)
                    AliPayResult.DUPLICATED.code -> onFailure(
                        it["memo"] ?: AliPayResult.DUPLICATED.desc
                    )
                    AliPayResult.CANCEL.code -> onFailure(it["memo"] ?: AliPayResult.CANCEL.desc)
                    AliPayResult.NETWORK.code -> onFailure(it["memo"] ?: AliPayResult.NETWORK.desc)
                    else -> onFailure(AliPayResult.UNKNOWN.desc)
                }
            }, {
                it.printStackTrace()
                onFailure(it.message ?: "")
            })
    }

    /**
     * 微信支付(回调在WXEntryActivity中)
     */
    fun wxPay(
        context: Context,
        entity: WXPayEntity,
        uiPosition:Int = 0
    ) {
        val msgApi = WXAPIFactory.createWXAPI(context, null)
        if (!msgApi.isWXAppInstalled) {
            ToastUtil.show(context.getString(R.string.wechat_not_install))
        } else {
            msgApi.registerApp(WX_APP_ID)
            msgApi.sendReq(PayReq().also {
                it.appId = WX_APP_ID
                it.partnerId = entity.partnerId
                it.prepayId = entity.prepayId
                it.packageValue = entity.packageValue
                it.nonceStr = entity.nonceStr
                it.sign = entity.sign
                it.timeStamp = entity.timestamp
                it.extData = uiPosition.toString()
            })
        }
    }
}

enum class AliPayResult(val code: String, val desc: String) {
    SUCCESS("9000", "支付成功"), FAILURE("4000", "支付失败"),
    DUPLICATED("5000", "订单重复"), CANCEL("6001", "取消支付"),
    NETWORK("6002", "网络异常"), UNKNOWN("6004", "未知错误")
}

data class PayResult(
    val paySuccess: Boolean = false,
    val payDesc: String = "",
    val uiPosition: Int=0
)

data class WXPayEntity(
    @SerializedName("appid")
    val appId: String = "",
    @SerializedName("partnerid")
    val partnerId: String = "",
    @SerializedName("prepayid")
    val prepayId: String = "",
    @SerializedName("timestamp")
    val timestamp: String = "",
    @SerializedName("noncestr")
    val nonceStr: String = "",
    @SerializedName("package")
    val packageValue: String = "",
    @SerializedName("sign")
    val sign: String = ""
)